import 'dart:convert';

import 'package:distribution_mall_flutter/constant/constant.dart';
import 'package:distribution_mall_flutter/constant/status_constant.dart';
import 'package:distribution_mall_flutter/entity/address/address_entity.dart';
import 'package:distribution_mall_flutter/entity/goods/detail/goods_detail_entity.dart';
import 'package:distribution_mall_flutter/entity/goods/goods.dart';
import 'package:distribution_mall_flutter/http/init.dart';
import 'package:distribution_mall_flutter/http/modules/goods.dart';
import 'package:distribution_mall_flutter/provider/common/pay.dart';
import 'package:distribution_mall_flutter/utils/debug.dart';
import 'package:distribution_mall_flutter/utils/storage.dart';
import 'package:easy_debounce/easy_debounce.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class PDetailsState {
  bool spread;
  GoodsDetailEntity? detail;
  bool firstLoading;


  // sku选中数量，key为id，value为数量
  Map<String, int> skuItems = {};
  bool calLoading = false;
  CalculateEntity? calculatePrice;

  PDetailsState(
      {
      this.spread = false,
      this.firstLoading = true,
      this.skuItems = const {},
      this.calculatePrice,
      this.calLoading = false,
      this.detail});

  PDetailsState.initial()
      :
        firstLoading = true,
        skuItems = const {},
        calLoading = false,
        spread = false;

  PDetailsState copyWith(
      {
      bool? spread,
      bool? firstLoading,
      List<dynamic>? addressInfo,
      List<String>? codeInfo,
      Map<String, int>? skuItems,
      GoodsDetailEntity? detail,
      bool? calLoading,
      CalculateEntity? calculatePrice}) {
    return PDetailsState(
      spread: spread ?? this.spread,
      detail: detail ?? this.detail,
      skuItems: skuItems ?? this.skuItems,
      calLoading: calLoading ?? this.calLoading,
      firstLoading: firstLoading ?? this.firstLoading,
      calculatePrice: calculatePrice ?? this.calculatePrice,
    );
  }

  get skuTotal {
    int total = 0;
    for (var item in skuItems.entries) {
      total += item.value;
    }
    return total;
  }

  List<Sale> get saleInfos {
    if (detail?.suInfo?.saleInfos?.isEmpty == true) return [];
    //   List<Sale> list = detail?.suInfo?.saleInfos?.toList() ?? [];
    //   list.sort((a, b) {
    //     if (a.onSale != true ||
    //         (a.stockNum != null && a.stockNum! <= 0) && b.onSale != true ||
    //         (b.stockNum != null && b.stockNum! <= 0)) return 0;
    //     if (a.onSale == true || (a.stockNum != null && a.stockNum! > 0)) {
    //       return -1;
    //     }
    //     if (b.onSale == true || (b.stockNum != null && b.stockNum! > 0)) {
    //       return 1;
    //     }
    //     return 0;
    //   });
    return detail?.suInfo?.saleInfos
            ?.where((item) => item.display == true)
            .toList() ??
        [];
  }

  List<Map<String, Object>> get orderItemGroupList {
    return skuItems.entries
        .where((item) => item.value > 0)
        .map((e) => {
      'saleItemId': e.key,
      'quantity': e.value,
    })
        .toList();
  }

  ///获取领样商品的订单物品信息
  List<Map<String, Object>> get sampleOrderItemGroupList {
    var allSale = sampleOrderItemList();
    // sku选中数量，key为id，value为数量
    Map<String, int> skuItems = {};
    for (var e in allSale!) {
      skuItems['${e.saleItemId}'] = e.stepQuantity ?? 1;
    }
    return skuItems.entries
        .map((e) => {
              'saleItemId': e.key,
              'quantity': e.value,
            })
        .toList();
  }

  /// sku商品
  Iterable<Sale> skuList() {
    return detail!.suInfo?.saleInfos?.where((e) =>
            (e.stockNum ?? 0) > 0 &&
            e.onSale == true &&
            skuItems.keys.contains(e.saleItemId)) ??
        [];
  }

  ///领样商品
  Iterable<Sale>? sampleOrderItemList() {
    return detail!.suInfo?.saleInfo?.saleSpecs?.where(
        (e) => (e.stockNum ?? 0) > 0 && e.onSale == true && e.sample == true);
  }
}

final pDetailProvider =
    StateNotifierProvider.autoDispose<PDetailViewModel, PDetailsState>((ref) {
  return PDetailViewModel();
});

class PDetailViewModel extends StateNotifier<PDetailsState> {
  PDetailViewModel() : super(PDetailsState.initial());


  Future getDetail(String? saleItemId) async {
    if (saleItemId == null || saleItemId.isEmpty) {
      state = state.copyWith(firstLoading: false);
      return;
    }
    try {
      Result<GoodsDetailEntity>? data =
          await GoodsApi.goodsRender({'saleItemId': saleItemId});
      if (data.data != null) {
        state = state.copyWith(detail: data.data, firstLoading: false);
      }
      return;
    } catch (e) {
      debugPrint('eeeeeee $e');
      state = state.copyWith(firstLoading: false);
    }
  }

  void triggerSpread() {
    state = state.copyWith(spread: !state.spread);
  }

  ///设置购买个数
  void setSkuItems(String? key, int value) {
    if (key == null || key.isEmpty) return;
    Map<String, int> skuItems = Map.from(state.skuItems);
    skuItems[key] = value;
    List<Map<String, dynamic>> list = [];
    state = state.copyWith(skuItems: skuItems);
    for (var item in skuItems.entries) {
      list.add({'saleItemId': item.key, 'quantity': item.value});
    }
    EasyDebounce.debounce(
        DeAndThrConstant.calPriceDe, const Duration(milliseconds: 500), () {
      getCalculatePrice(list);
    });
  }

  void getCalculatePrice(List arr) async {
    state = state.copyWith(calLoading: true);
    try {
      CalculateEntity? data =
          await GoodsApi.calculateChoiceItemPrice({'saleItemChoiceInfo': arr});
      if (data == null) return;
      state = state.copyWith(calculatePrice: data, calLoading: false);
    } catch (e) {
      state = state.copyWith(calLoading: false);
    }
  }

  get getSaleInfoLength {
    return state.detail?.suInfo?.saleInfos?.length ?? 0;
  }

  void setFirstLoading(bool firstLoading) {
    state = state.copyWith(firstLoading: firstLoading);
  }
}
